﻿using BusinessEntity;
using BusinessRepository;
using BusinessRule.Organization;
using learun.util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
    public class ProFuKuanYJHRule
    {
        #region 付款计划

        #region 导出
        /// <summary>
        /// 用户列表（导出Excel）
        /// </summary>
        /// <returns></returns>
        public static async Task<MemoryStream> GetExportFKYJHList(List<string> ids, List<ColumnModel> cols)
        {
            //List<string> ids = new List<string>();
            //List<ColumnModel> cols = new List<ColumnModel>();

            //取出数据源
            DataTable exportTable = await GetExportFKYJHList(ids);
            //设置导出格式
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.Title = "投资计划信息";
            excelconfig.TitleFont = "微软雅黑";
            excelconfig.TitlePoint = 25;
            //excelconfig.HeadPoint = 12;
            excelconfig.FileName = "投资计划信息.xls";
            excelconfig.IsAllSizeColumn = true;
            //每一列的设置,没有设置的列信息，系统将按datatable中的列名导出
            excelconfig.ColumnEntity = new List<ColumnModel>();
            for (int i = 0; i < cols.Count; i++)
            {
                excelconfig.ColumnEntity.Add(new ColumnModel() { Column = cols[i].Column, ExcelColumn = cols[i].ExcelColumn });
            }

            return ExcelHelper.ExportMemoryStream(exportTable, excelconfig);
        }

        public async static Task<DataTable> GetExportFKYJHList(List<string> ids)
        {
            //throw new NotImplementedException();
            string yids = string.Join("','", ids);
            yids = "'" + yids + "'";
            string strsql = "select * from View_ProFKYJHLists where id in (" + yids + ")";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        #endregion

        public static async Task<(IEnumerable<dynamic>, int)> GetAddHTFKYJHIndex(dynamic fkyjh, string strdepids)//struid
        {
            string dxmc = fkyjh.dxmc;
            string htid = fkyjh.htid;
            string htbh = fkyjh.htbh;

            string xmmc = fkyjh.xmmc;
            string bytb = fkyjh.bytb;
            string bywtb = fkyjh.bywtb; 

            string status = fkyjh.status;

            string htmc = fkyjh.htmc;

            string current = fkyjh.current;
            string size = fkyjh.size;
            string sort = fkyjh.sort;
            string column = fkyjh.column;

            //fkyjh.htid = htid;
            //fkyjh.xmmc = xmmc;
            //fkyjh.bytb = bytb;

            //fkyjh.status = status;
            //fkyjh.current = current;
            //fkyjh.size = size;
            //fkyjh.sort = sort;
            //fkyjh.column = column;

            //查询列表
            string str = "";
            if (!(string.IsNullOrEmpty(dxmc)))
            {
                str = str + " and dxmc like '%" + dxmc + "%'";
            }
            if (!(string.IsNullOrEmpty(xmmc)))
            {
                str = str + " and xmmc like ''%" + xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(htid)))
            {
                str = str + " and htid like ''%" + htid + "%'";
            }
            if (!(string.IsNullOrEmpty(htbh)))
            {
                str = str + " and htbh like ''%" + htbh + "%'";
            }
            if (!(string.IsNullOrEmpty(htmc)))
            {
                str = str + " and htmc like ''%" + htmc + "%'";
            }


            if (!(string.IsNullOrEmpty(status)))
            {
                str = str + " and spstatus = ''" + status + "''";
            }
            else
            {
                str = str + " and spstatus = ''checked''";
            }

            if (!(string.IsNullOrEmpty(bytb)))
            {
                str = str + " and id in (select htid from CProFKYJH where months = '" + bytb + "' )";
            }

            if (!(string.IsNullOrEmpty(bywtb)))
            {
                str = str + " and id not in (select htid from CProFKYJH where months = '" + bywtb + "' )";
            }


            str += " and xmid not in (select xmid from CProGD)";

            string sql = "select * from View_ProHTLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = sort.ToLower() == "asc" ? true : false;
            string strcolumn = "";
            if (string.IsNullOrEmpty(column))
            {
                strcolumn = "id";
            }
            //int size = size.ToInt();
            //int current = current.ToInt();
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, strcolumn, isAsc, size.ToInt(), current.ToInt());
        }

        public static async Task<(IEnumerable<dynamic>, int)> GetHTFKYJHIndex(dynamic fkyjh, string strdepids)//string struid
        {

            string dxmc = fkyjh.dxmc;
            string month = fkyjh.month;
            string xmmc = fkyjh.xmmc;
            string fkxmc = fkyjh.fkxmc;

            string htmc = fkyjh.htmc;

            string status = fkyjh.status;
            string current = fkyjh.current;
            string size = fkyjh.size;
            string sort = fkyjh.sort;
            string column = fkyjh.column;

            string str = "";
            if (!(string.IsNullOrEmpty(month)))
            {
                str = str + " and months = ''" + CommonHelper.ParseDateTime(month + "01").ToString("yyyy-MM") + "'";
            }
            if (!(string.IsNullOrEmpty(dxmc)))
            {
                str = str + " and dxmc like '%" + dxmc + "%'";
            }
            if (!(string.IsNullOrEmpty(xmmc)))
            {
                str = str + " and xmmc like ''%" + xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(htmc)))
            {
                str = str + " and htmc like ''%" + htmc + "%'";
            }
            if (!(string.IsNullOrEmpty(fkxmc)))
            {
                str = str + " and jhfkx like ''%" + fkxmc + "%''";
            }

            if (!(string.IsNullOrEmpty(status)))
            {
                str = str + " and spstatus = ''" + status + "''";
            }

            str += " and xmid not in (select xmid from CProGD)";

            string sql = "select * from View_ProFKYJHLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = sort.ToLower() == "asc" ? true : false;
            //string strcolumn = "";
            if (string.IsNullOrEmpty(column.ToString()))
            {
                column = "id";
            }
            //int size = dic["size"].ToInt();
            //int current = dic["current"].ToInt();
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size.ToInt(), current.ToInt());
        }

        //public static async Task<(IEnumerable<dynamic>, int)> GetAddHTFKYJHIndex(Dictionary<string, string> dic, string strdepids)//struid
        //{
        //    //查询列表
        //    string str = "";
        //    if (!(string.IsNullOrEmpty(dic["dxmc"])))
        //    {
        //        str = str + " and dxmc like '%" + dic["dxmc"].ToString() + "%'";
        //    }
        //    if (!(string.IsNullOrEmpty(dic["xmmc"])))
        //    {
        //        str = str + " and xmmc like ''%" + dic["xmmc"].ToString() + "'";
        //    }
        //    if (!(string.IsNullOrEmpty(dic["htid"])))
        //    {
        //        str = str + " and htid like ''%" + dic["htid"].ToString() + "'";
        //    }


        //    if (!(string.IsNullOrEmpty(dic["status"])))
        //    {
        //        str = str + " and spstatus = ''" + dic["status"].ToString() + "''";
        //    }
        //    if (!(string.IsNullOrEmpty(dic["bytb"])))
        //    {
        //        if (dic["bytb"].ToString() == "1")
        //        {
        //            str = str + " and id in (select htid from CProFKYJH where months = '" + DateTime.Now.Month + "' )";
        //        }
        //        else
        //        {
        //            str = str + " and id not in (select htid from CProFKYJH where months = '"+ DateTime.Now.Month +"' )";
        //        }
        //    }


        //    //string struid = ContextHelper.Userid();

        //    //await UserRule.GetUserDepid(struid)
        //    string sql = "select * from View_ProHTLists where departid in " + strdepids + str.Replace("''", "'");
        //    bool isAsc = dic["sort"].ToString().ToLower() == "asc" ? true : false;
        //    string column = "";
        //    if (string.IsNullOrEmpty(dic["column"].ToString()))
        //    {
        //        column = "id";
        //    }
        //    int size = dic["size"].ToInt();
        //    int current = dic["current"].ToInt();
        //    return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size, current);
        //}



        //public static async Task<(IEnumerable<dynamic>, int)> GetHTFKYJHIndex(Dictionary<string, string> dic, string strdepids )//string struid
        //{
        //    //dynamic d, 
        //    //string ss = d.month;
        //    //string month = d.month;


        //    string str = "";
        //    if (!(string.IsNullOrEmpty(dic["month"])))
        //    {
        //        str = str + " and months = ''" + dic["month"].ToString() + "'";
        //    }
        //    if (!(string.IsNullOrEmpty(dic["dxmc"])))
        //    {
        //        str = str + " and dxmc like '%" + dic["dxmc"].ToString() + "%'";
        //    }
        //    if (!(string.IsNullOrEmpty(dic["xmmc"])))
        //    {
        //        str = str + " and xmmc like ''%" + dic["xmmc"].ToString() + "'";
        //    }

        //    if (!(string.IsNullOrEmpty(dic["fkxmc"])))
        //    {
        //        str = str + " and jhfkx like ''%" + dic["fkxmc"].ToString() + "%''";
        //    }

        //    if (!(string.IsNullOrEmpty(dic["status"])))
        //    {
        //        str = str + " and spstatus = ''" + dic["status"].ToString() + "''";
        //    }

        //    //string struid = ContextHelper.Userid();
        //    //await UserRule.GetUserDepid(struid)
        //    string sql = "select * from View_ProFKYJHLists where departid in " + strdepids + str.Replace("''", "'");
        //    bool isAsc = dic["sort"].ToString().ToLower() == "asc" ? true : false;
        //    string column = "";
        //    //if (querry.sort != "Asc" && querry.sort != "asc")
        //    //{
        //    //    isAsc = false;
        //    //}
        //    if (string.IsNullOrEmpty(dic["column"].ToString()))
        //    {
        //        column = "id";
        //    }
        //    int size = dic["size"].ToInt();
        //    int current = dic["current"].ToInt();
        //    return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size, current);
        //}

        public async static Task<IEnumerable<dynamic>> GetHTFKYJH(string htid)
        {
            //throw new NotImplementedException();

            string strsql = "select * from View_ProFKYJHLists where tid = '" + htid + "'";
            return await new RepositoryFactory().BaseRepository().FindList(strsql);
        }

        public async static Task<dynamic> GetHTFKYJHByid(string jhid)
        {
            //throw new NotImplementedException();

            string strsql = "select * from View_ProFKYJHLists where id = '" + jhid + "'";
            return await new RepositoryFactory().BaseRepository().FindList(strsql);
        }

        public async static Task<int> InsertHTYJH(CProFKYJH fkyjh, string ope)
        {
            if (ope == "add")
            {
                //fkyjh.status = BaseEditPower.GetSPEnumValue("待提交");

                return await new RepositoryFactory().BaseRepository().Insert(fkyjh);
            }
            else// (ope == "edit")
            {
                return await new RepositoryFactory().BaseRepository().Update(fkyjh);
            }
        }

        public async static Task<bool> DeleteHTFKYJH(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    await irp.DeleteAny<CProFKYJH>(new { id = idm.id });
                }
                return true;
            });
        }
        #endregion

        #region 付款申请
        //审核金额限制
        public async static Task<DataTable> GetSHJEXZ(string jhid,string sqid)
        {
            //throw new NotImplementedException();
            string strsql = @"select*,shje-sqje ksqje from(
select shje, isnull((select sum(sqje) from CProFKSQ where jhid = tfkjh.id and id <> '"+ sqid +"'),0)sqje from CProFKYJH tfkjh where id = '"+ jhid +"')t ";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }

        //合同主键id
        public async static Task<DataTable> GetSHJEXZ2(string htid, string sqid)
        {
            //throw new NotImplementedException();
            string strsql = @"select *,ISNULL(yingfu,0)-ISNULL(sqje,0) ksqje from (
select sum(sqje)sqje,(select yingfu from View_FKJHTOYFJE where id = '" + htid + @"')yingfu
 from CProFKSQ where htid = '"+ htid +"' and id<> '" + sqid + "')t ";
            return await new RepositoryFactory().BaseRepository().FindTable(strsql);
        }


        public async static Task<IEnumerable<dynamic>> GetHTFKSQ(string htid)
        {
            //throw new NotImplementedException();
            string strsql = "select * from View_ProFKSQLists where tid = '" + htid + "'";
            return await new RepositoryFactory().BaseRepository().FindList(strsql);
        }

        public async static Task<dynamic> GetHTFKSQByid(string id)
        {
            //throw new NotImplementedException();
            string strsql = "select * from View_ProFKSQLists where id = '" + id + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(strsql);
        }

        public async static Task<int> InsertHTFKSQ(CProFKSQ fksq, string ope)
        {
            if (ope == "add")
            {
                //fksq.status = BaseEditPower.GetSPEnumValue("待提交");

                return await new RepositoryFactory().BaseRepository().Insert(fksq);
            }
            else// (ope == "edit")
            {
                return await new RepositoryFactory().BaseRepository().Update(fksq);
            }
        }

        public async static Task<bool> DeleteHTFKSQ(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    await irp.DeleteAny<CProFKSQ>(new { id = idm.id });
                }
                return true;
            });
        }

        #endregion

        #region 付款明细
        //付款明细-根据sqid获取付款明细
        public static async Task<IEnumerable<dynamic>> GetFKMXBysqid(string sqid)
        {
            string sql = "select * from CProFKMX where sqid = '" + sqid + "' order by zfrq desc";
            return await new RepositoryFactory().BaseRepository().FindList(sql, null);
        }
        //付款明细-根据fkid获取单条付款明细
        public static async Task<IEnumerable<dynamic>> GetFKMXByfkid(string fkid)
        {
            string sql = "select * from CProFKMX where id = '" + fkid + "' order by zfrq desc";
            return await new RepositoryFactory().BaseRepository().FindList(sql, null);
        }

        //新增修改付款明细
        public static async Task InsertCProFKMX(List<CProFKMX> fkmx, string strlx)
        {
            TranstionRule.GetRunActionTransAsync(async irp =>
            {
                if (strlx == "add")
                {
                    for (int i = 0; i < fkmx.Count; i++)
                    {
                        await irp.Insert(fkmx[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < fkmx.Count; i++)
                    {
                        await irp.Update(fkmx[i]);
                    }
                }
               

                return true;
            });


           
        }


        //新增修改付款明细
        public static async Task InsertCProFKMX(CProFKMX fkmx, string strlx)
        {
            if (strlx == "add")
            {
                await new RepositoryFactory().BaseRepository().Insert(fkmx);
            }
            else
            {
                await new RepositoryFactory().BaseRepository().Update(fkmx);
            }
        }

        //删除多条付款明细
        public static async Task<bool> DeleteCProFKMXMulti(Root ids)
        {
            return await TranstionRule.GetRunActionTransAsync(async irp =>
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    string delsql = "delete from CProFKMX where id = '" + idm.id + "'";

                    await irp.ExecuteSql(delsql);
                }
                return true;

            });
        }
        #endregion
    }
}
